/*
 * @Author: shawnxiao
 * @Date: 2021-02-01 16:40:41
 * @LastEditTime: 2022-01-04 16:53:10
 * @FilePath: /vite2-vue3-typescript/src/store/modules/app.ts
 */
import * as request from '@/apis/Login'
import { setStorage } from '@/common/utils/storage'
import { getTokenKeyForPage } from '@/common/utils'

import { AppState } from '@/types/store'
import { Module } from 'vuex'

// 取页面名来区分不同的token
const tokenKeyPage = getTokenKeyForPage()
export const LANG = 'LANGUAGE_VITE_TS_VUE3' // 语言

const state: any = () => ({
  tokenId: '',
  isLogin: false,
  device: 'desktop',
  language: localStorage.getItem(LANG) || 'zh',
  collapse: true,
})

const getters = {
  tokenId: (state: AppState) => state.tokenId,
  isLogin: (state: AppState) => state.isLogin,
  device: (state: AppState) => state.device,
  language: (state: AppState) => state.language,
  collapse: (state: AppState) => state.collapse,
}

const mutations = {
  TOGGLE_COLLAPSE(state: AppState) {
    state.collapse = !state.collapse
  },
  TOGGLE_DEVICE(state: AppState, device: string) {
    state.device = device
  },
  SET_LOGIN_STATUS(state: AppState, status: boolean) {
    state.isLogin = status
  },
  SET_LANGUAGE(state: AppState, language: string) {
    // 设置缓存
    localStorage.setItem(LANG, language)
    // 修改状态
    state.language = language
  },
  SET_TOKEN_ID(state: AppState, tokenId: string) {
    state.tokenId = tokenId
    setStorage(tokenKeyPage, tokenId)
  },
}

const actions = {
  toggleCollapse({ commit }: any) {
    commit('TOGGLE_COLLAPSE')
  },
  toggleDevice({ commit }: any, device: string) {
    commit('TOGGLE_DEVICE', device)
  },
  setLoginStatus({ commit }: any, status: boolean) {
    commit('SET_LOGIN_STATUS', status)
  },
  setLanguage({ commit }: any, language: string) {
    commit('SET_LANGUAGE', language)
  },
  setTokenId({ commit }: any, tokenId: string) {
    commit('SET_TOKEN_ID', tokenId)
    commit('SET_LOGIN_STATUS', !!tokenId)
  },
  generateToken({ dispatch }: any) {
    // 生成token
    return new Promise((resolve, reject) => {
      request
        .checkLoginTokenFn({})
        .then((res: any) => {
          const status = !!(res?.data?.login && res?.data?.binding && res?.data?.tokenId)
          if (status) {
            dispatch('setTokenId', res.data.tokenId)
          }
          resolve(status)
        })
        .catch((err) => {
          reject(err)
        })
    })
  },
}
const appModule: Module<AppState, any> = { namespaced: true, state, getters, mutations, actions }

export default appModule
